/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.service.impl;

import com.huawei.housekeeper.common.enums.ErrorCode;
import com.huawei.housekeeper.commonutils.constants.DeletedFlagEnum;
import com.huawei.housekeeper.commonutils.constants.RabbitMqTopicConfig;
import com.huawei.housekeeper.commonutils.constants.TaskOrderAction;
import com.huawei.housekeeper.commonutils.entity.MessageServiceEntity;
import com.huawei.housekeeper.commonutils.entity.OrderMessageEntity;
import com.huawei.housekeeper.commonutils.exception.Assert;
import com.huawei.housekeeper.commonutils.utils.CommonUtil;
import com.huawei.housekeeper.commonutils.utils.CopyUtils;
import com.huawei.housekeeper.commonutils.utils.JsonUtil;
import com.huawei.housekeeper.commonutils.utils.MessageServiceUtil;
import com.huawei.housekeeper.dao.entity.Task;
import com.huawei.housekeeper.dao.mapper.TaskMapper;
import com.huawei.saashousekeeper.annotation.MqAround;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;

import lombok.extern.log4j.Log4j2;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Date;

/**
 * 功能描述 接受来自订单服务发送来的消息，生成相应的任务
 *
 * @since 2022-03-03
 */
@Log4j2
@Service
public class RabbitMqOrderServiceImpl {
    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private MessageServiceUtil messageServiceUtil;

    /**
     * 接受来自订单服务发送来的消息，生成相应的任务
     *
     * @param message
     * @param tenantDomain
     * @throws JsonProcessingException 消息转换异常
     */
    @MqAround
    @RabbitListener(queues = {RabbitMqTopicConfig.QUEUE_TASK})
    public void receiveOrderMsgFromMsgService(@Header(RabbitMqTopicConfig.RABBITMQ_HEADER_TENANT) String tenantDomain,
        @Payload String message) throws JsonProcessingException {
        Assert.notNull(message, ErrorCode.TENANT_MISS_ERROR.getCode(), ErrorCode.MESSAGE_ERROR.getMessage());
        Assert.notNull(tenantDomain, ErrorCode.TENANT_MISS_ERROR.getCode(), ErrorCode.TENANT_MISS_ERROR.getMessage());

        OrderMessageEntity orderMessageEntity = JsonUtil.jsonToPojo(message, OrderMessageEntity.class);
        Task taskEntity = buildTask(orderMessageEntity);

        LambdaQueryWrapper<Task> selectQuery = Wrappers.lambdaQuery();
        selectQuery.eq(Task::getOrderId, taskEntity.getOrderId());
        selectQuery.eq(Task::getDeleteFlag, DeletedFlagEnum.SERVICE_FLAGE_UNDELETED.getCode());
        selectQuery.ne(Task::getTaskStatus, TaskOrderAction.TASK_ORDER_CANCEL.getAction());
        Task oldTask = taskMapper.selectOne(selectQuery);
        boolean isSuccess = false;
        if (oldTask == null) {
            taskMapper.insert(taskEntity);
            isSuccess = true;
        }
        sendMsgToMsgService(orderMessageEntity, isSuccess);
    }

    /**
     * 订单创建成功后发送消息
     *
     * @param orderMessageEntity
     * @throwsJsonProcessingException
     */
    private void sendMsgToMsgService(OrderMessageEntity orderMessageEntity, boolean isSuccess)
        throws JsonProcessingException {
        String msgTempage = "";
        String title = "";
        if (isSuccess) {
            msgTempage = "附近有{0}服务的派单，请留意!";
            title = "任务大厅：来自【" + orderMessageEntity.getCustomerName() + "】的订单消息";
        } else {
            msgTempage = "{0}服务的订单任务已存在!";
            title = "任务大厅：订单任务失败";
        }
        msgTempage = MessageFormat.format(msgTempage, orderMessageEntity.getServiceName());
        MessageServiceEntity messageServiceEntity = new MessageServiceEntity();
        messageServiceEntity.setTime(new Date());
        messageServiceEntity.setTitle(title);
        messageServiceEntity.setMsg(msgTempage);
        messageServiceEntity.setUserId(orderMessageEntity.getCustomerId());
        messageServiceUtil.sendMsgToMsgService(RabbitMqTopicConfig.MESSAGE_TASK_ORDER, messageServiceEntity);
    }

    /**
     * 根据mq消息初始化任务实体
     *
     * @param orderMessageEntity
     * @return {@link Task}
     * @throws JsonProcessingException
     */
    private Task buildTask(OrderMessageEntity orderMessageEntity) throws JsonProcessingException {
        Task taskEntity = new Task();
        String serviceDetail = JsonUtil.objectToJson(orderMessageEntity.getServiceDetail());
        CopyUtils.copyProperties(orderMessageEntity, taskEntity);
        taskEntity.setTaskStatus(TaskOrderAction.TASK_ORDER_WAITING.getAction());
        taskEntity.setVersion(CommonUtil.getUUID());
        taskEntity.setSalary(orderMessageEntity.getPayment());
        taskEntity.setServiceDetail(serviceDetail);
        taskEntity.setDeleteFlag(DeletedFlagEnum.SERVICE_FLAGE_UNDELETED.getCode());
        taskEntity.setAppointmentTime(orderMessageEntity.getAppointment());
        return taskEntity;
    }
}